package demo11;


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
public class Solution {

    //1.二叉搜索树的最近公共祖先(二叉搜索树性质)
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        //保证让 p.val < q.val;
        if(p.val > q.val) {
            return lowestCommonAncestor(root, q, p);
        }
        TreeNode cur = root;
        while(cur != null) {
            if(cur.val > q.val) {
                cur = cur.left;
            } else if(cur.val < p.val) {
                cur = cur.right;
            } else {
                return cur;
            }
        }
        return cur;
    }

    //2.二叉搜索树中的插入操作(建树)
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if(root == null) {
            return new TreeNode(val);
        }
        TreeNode cur = root;
        TreeNode prev = null;
        while(cur != null) {
            prev = cur;
            if(cur.val > val) {
                //向左
                cur = cur.left;
            } else {
                //向右
                cur = cur.right;
            }
        }
        if(prev.val > val) {
            prev.left = new TreeNode(val);
        } else {
            prev.right = new TreeNode(val);
        }
        return root;
    }

    //3.修剪二叉搜索树(dfs)
    public TreeNode trimBST(TreeNode root, int low, int high) {
        if(root == null) {
            return null;
        }
        if(root.val < low) {
            return trimBST(root.right, low, high);
        }
        if(root.val > high) {
            return trimBST(root.left, low, high);
        }
        root.left = trimBST(root.left, low, high);
        root.right = trimBST(root.right, low, high);
        return root;
    }

}
